package jobteam.contacteventstocalendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.provider.ContactsContract.RawContacts.Data;
import android.util.Log;
import android.widget.Toast;

public class InsertContactsEventToCalendarActivity extends Activity {
	String TAG = "InsertContactsEventToCalendarActivity";

	private Uri CalendarVersionURI;
	private Context m_context;

	private static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
		ContactsContract.Data.DATA1,
		ContactsContract.Data.DATA2,
		ContactsContract.Data.MIMETYPE,
		ContactsContract.Data.RAW_CONTACT_ID
	};

	ArrayList<ContactEventInfo> m_ContactEventInfo = new ArrayList<ContactEventInfo>();
	String mode;
	Handler ConnectDB = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			for(int i = 0 ; i < m_ContactEventInfo.size() ; i++){
				String descriptionSTR = m_ContactEventInfo.get(i).ContactName;
				String rruleSTR = "FREQ=YEARLY;WKST=SU";

				if(m_ContactEventInfo.get(i).ContactEventType == 1)
					descriptionSTR = "ANNIVERSARY with " + descriptionSTR;

				else if(m_ContactEventInfo.get(i).ContactEventType == 3)
					descriptionSTR += "'s Birthday";

				else
					descriptionSTR += "'s Event";

				/*
				String[] CALENDAR_EVENT_PROJECTION = new String[] {
					   "_id",                       // 0                     - INTEGER PRIMARY KEY,
		               "calendar_id",               // 1 calendar account id - INTEGER
		               "description",               // 2 description - description - TEXT
		               "title",                     // 3 title - summary - TEXT
		               "dtstart",                   // 4 startTime - INTEGER
		               "dtend",                     // 5 endTime - INTEGER
		               "eventLocation",             // 6 location - TEXT
		               "rrule",                     // 7 rule - recurrence - TEXT
		               "eventStatus",               // 8 eventStatus - INTEGER ( tentative, confirm, cancelled)
		               "hasAlarm"                   // 9 hasAlarm <- (alarmDate - REMINDER(minutes) ) - INTEGER
			     };
				final Cursor cursorEvent = getContentResolver().query(CalendarVersionURI,
			  			CALENDAR_EVENT_PROJECTION, null, null, "calendar_id" + " ASC");
				cursorEvent.moveToFirst();
				while(cursorEvent.getInt(cursorEvent.getColumnIndex("_id")) == 7){
					cursorEvent.moveToNext();
				}
				long tmp = cursorEvent.getLong(cursorEvent.getColumnIndex("dtstart"));
				Date tmpdate = new Date(tmp);
				long tmplong = tmpdate.getTime();
				 */

				
					int index = m_ContactEventInfo.get(i).ContactEvent.indexOf("-", 1);
					int year = Calendar.getInstance().get(Calendar.YEAR);
					String timezonestr = Calendar.getInstance().getTimeZone().getDisplayName(Locale.getDefault());
					int month = 0, day = 0;
	
					/*
					Log.d(TAG, m_ContactEventInfo.get(i).ContactEvent + " index: " + index);
					Log.d(TAG, m_ContactEventInfo.get(i).ContactEvent);
	
					if(index != 1 && isYearly)
						year = Integer.parseInt(m_ContactEventInfo.get(i).ContactEvent.substring(index - 4, index));*/
					//월일 표시만 있을 경우 "--03-05" 로 텍스트 표현, 년도 표시 있을 경우 "1984-10-12"로 표현
				if(!mode.equals("addLunar")){
					month = Integer.parseInt(m_ContactEventInfo.get(i).ContactEvent.substring(index + 1, index + 3));
					day = Integer.parseInt(m_ContactEventInfo.get(i).ContactEvent.substring(index + 4, index + 6));
				}
				else{
					LunaDate LunarOBJ = new LunaDate(year, 
							Integer.parseInt(m_ContactEventInfo.get(i).ContactEvent.substring(index + 1, index + 3)), 
							Integer.parseInt(m_ContactEventInfo.get(i).ContactEvent.substring(index + 4, index + 6)));
					Date dateOBJ = LunarOBJ.toSolarDate();
					month = dateOBJ.getMonth(); day = dateOBJ.getDate();
				}
				
				Date startTime = new Date(year - 1900, month - 1 , day, 0, 0, 0);

				ContentValues contentValue = new ContentValues();
				contentValue.put("calendar_id", 1);                  	//Account ID     
				contentValue.put("title", descriptionSTR);            	//Title
				contentValue.put("description", descriptionSTR);  		//Description
				contentValue.put("dtstart", startTime.getTime()); 		//StartTime
				contentValue.put("eventTimezone", timezonestr); 		//timeline
				contentValue.put("dtend", new Date(year - 1900, month - 1, day, 23, 59, 59).getTime());
				//contentValue.put("allDay", 1); 							//allDay true
				if(mode.equals("addYearly")){
					contentValue.put("rrule", rruleSTR); 					//rrule
					contentValue.put("duration", "P1D"); 					//TimeDuration
				}
				
				getContentResolver().insert(CalendarVersionURI, contentValue);
			}
			InsertEventComplete();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		m_context = this;
		Intent intent = getIntent();
		if(!intent.hasExtra("ContactIDArr")){
			Log.d("addContactEventActivity", "error");
			return;
		}
		ArrayList<Integer>ContactIDarray = intent.getIntegerArrayListExtra("ContactIDArr");
		mode = intent.getStringExtra("mode");
		m_ContactEventInfo = getContactEventList(ContactIDarray);

		Log.d("addContactEventActivity", "m_ContactEventInfo build Complete");

		if(Build.VERSION.RELEASE.substring(0, 2).equals("1."))
			CalendarVersionURI = Uri.parse("content://"+ "calendar" +"/events");
		else if(Build.VERSION.RELEASE.contains("2.0"))
			CalendarVersionURI = Uri.parse("content://"+ "calendar" +"/events");
		else if(Build.VERSION.RELEASE.contains("2.1"))
			CalendarVersionURI = Uri.parse("content://"+ "calendar" +"/events");
		else if(Build.VERSION.RELEASE.contains("2.2"))
			CalendarVersionURI = Uri.parse("content://"+ "com.android.calendar" +"/events");
		else if(Build.VERSION.RELEASE.contains("2.3"))
			CalendarVersionURI = Uri.parse("content://"+ "com.android.calendar" +"/events");
		else
			CalendarVersionURI = Uri.parse("content://"+ "com.android.calendar" +"/events");
		//*******************************************
		//Toast.makeText(this, "Adding selected events", Toast.LENGTH_SHORT).show();
		new AlertDialog.Builder(this)
		.setTitle("Check sure")
		.setMessage(getResources().getString(R.string.Check_Add_Event_to_Calendar) + "?")
		.setIcon(R.drawable.icon)
		.setCancelable(false)
		.setPositiveButton(R.string.Confirm, new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int whichButton){
				ConnectDB.sendEmptyMessage(0);
			}
		})
		.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
				Toast.makeText(m_context, R.string.Cancel, Toast.LENGTH_SHORT).show();
			}
		}).show();
	}

	private void InsertEventComplete(){
		new AlertDialog.Builder(this)
		.setTitle("Insert complete.")
		.setMessage(getResources().getString(R.string.Add_Event_to_Calendar))
		.setIcon(R.drawable.icon)
		.setCancelable(false)
		.setPositiveButton(R.string.Confirm, new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int whichButton){
				finish();
			}
		}).show();
	}

	private ArrayList<ContactEventInfo> getContactEventList(ArrayList<Integer> contactidArr){
		ArrayList<ContactEventInfo> returnValue = new ArrayList<ContactEventInfo>(); 
		Uri ContactBaseUri = ContactsContract.Data.CONTENT_URI;
		for(int i = 0 ; i < contactidArr.size() ; i++){
			Cursor cursor = this.getContentResolver().query(ContactBaseUri, 
					CONTACTS_SUMMARY_PROJECTION, 
					Data.RAW_CONTACT_ID + " = " + contactidArr.get(i), null, null);
			int ContactID = contactidArr.get(i);
			String ContactEvent = "";
			String ContactName = "";
			int ContactEventType = 0;
			if(cursor.moveToFirst()){
				for(int j = 0 ; j < cursor.getCount() ; j++){
					if(cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).equals(Event.CONTENT_ITEM_TYPE)){
						ContactEvent = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
						ContactEventType = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA2)));
					}
					else if(cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).
							equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)){
						ContactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
					}
					cursor.moveToNext();
				}
				returnValue.add(new ContactEventInfo(ContactID, ContactName, ContactEvent, ContactEventType));
			}
			cursor.close();
		}
		return returnValue;
	}

	public class ContactEventInfo{
		public int ContactID;
		public String ContactName;
		public String ContactEvent;
		public int ContactEventType;

		public ContactEventInfo(int contactid, String contactname, String contactevent, int contacteventtype) {
			ContactID = contactid;
			ContactName = contactname;
			ContactEvent = contactevent;
			ContactEventType = contacteventtype;
		}
	}
}
